﻿namespace ArisanNgocok.Controllers
{
	using System;
	using System.Collections.Generic;
	using System.Data.Entity;
	using System.Linq;
	using System.Security.Permissions;
	using System.Web.Mvc;
	using Models;
	using ViewModels;
	using Provider;

   public class HomeController : Controller
   {
	  public ActionResult Index()
	  {
		 return View();
	  }

	  public ActionResult Ngobrol()
	  {
		 return View();
	  }

	  public ActionResult Status(string periode = null, bool edit = false)
	  {
		  int year = DateTime.Now.Year;
		  int month = DateTime.Now.Month;

		  if(!string.IsNullOrEmpty(periode) && !string.IsNullOrWhiteSpace(periode) && periode.IndexOf('-')>-1)
		  {
			  string[] tokens = periode.Split(new char[] { '-' });
			  if (tokens.Length == 2)
			  {
				  try
				  {
					  year = int.Parse(tokens[0]);
					  month = int.Parse(tokens[1]);
				  }catch(FormatException fx)
				  {
					  year = DateTime.Now.Year;
					  month = DateTime.Now.Month;
				  }
			  }
		  }

		  periode = year + "-" + month;

		  using (var db = new DataContext())
		  {
			  var payments = from us in db.Users
							 join py in db.Payments
							   on us.Id equals py.User.Id
							   into pyx
							 from p in pyx.Where(px => px.Year == year && px.Month == month).DefaultIfEmpty()
							 orderby p.User.Name
							 select new UserPaymentsViewModel()
							 {
								 CreationDate = p.CreationDate,
								 IsPaid = p.IsPaid,
								 ModifiedDate = p.ModifiedDate,
								 Month = p.Month,
								 PaymentID = p.Id,
								 UserId = us.Id,
								 UserName = us.Name,
								 Year = p.Year,
								 HasSelected = db.SelectedUser.Select(ux => ux.User).Contains(p.User)
							 };
			  var periodeList = db.Payments
				  .Select(o => new { Year = o.Year, Month = o.Month })
				  .OrderBy(o => o.Year).ThenBy(o => o.Month)
				  .Distinct()
				  .ToList()
				  .Select(o => new SelectListItem()
				  {
					  Text = new DateTime(o.Year, o.Month, 1).ToString("MMM yyyy"),
					  Value = o.Year + "-" + o.Month,
					  Selected = o.Year == year && o.Month == month
				  })
				  .ToList();

			  if (periodeList.Count() == 0)
			  {
				  periodeList.Add(new SelectListItem()
				  {
					  Text = new DateTime(year, month, 1).ToString("MMM yyyy"),
					  Value = periode,
					  Selected = true
				  });
			  }

			  ViewBag.Edit = edit;
			  ViewBag.PeriodeList = periodeList;
			  ViewBag.LastModified = db.Payments.Where(o => o.Year == year && o.Month == month)
				  .Select(o => o.ModifiedDate).Max();

			  return View(payments.ToList()); ;
		  }
	  }

	  public ActionResult Toggle(string paymentId)
	  {
		 new ServiceManager().TogglePaymentStatus(Guid.Parse(paymentId));
		 return RedirectToAction("Status", new {edit =true});
	  }
   }
}